package service

import (
	"sync"

	"github.com/beego/beego/v2/core/config"
	"github.com/beego/beego/v2/core/logs"

	"gitee.com/wangxj0826/experiment-codes/service-pressure-test/api"
	"gitee.com/wangxj0826/experiment-codes/service-pressure-test/db"
	"gitee.com/wangxj0826/experiment-codes/service-pressure-test/util"
)

type userinfo struct {
	cache *util.Cache
}

var userinfoImpl *userinfo
var userinfoInit sync.Once

func GetUserInfoSvc() userinfo {
	userinfoInit.Do(func() {
		var cache *util.Cache
		usecache, _ := config.Bool("usecache")
		if usecache {
			cache = util.New(20)
			logs.Info("user cache inited")
		}
		userinfoImpl = &userinfo{cache: cache}
	})
	return *userinfoImpl
}

func (s userinfo) GetUserByID(id int) (*api.User, error) {
	var user *api.User
	var err error
	if s.cache != nil {
		v, ok := s.cache.Get(id)
		if ok {
			logs.Debug("catch it")
			return v.(*api.User), nil
		}
	}
	user, err = db.ReadUserByID(int64(id))
	if err != nil {
		logs.Error("err: %v", err)
		return nil, err
	}
	if s.cache != nil {
		logs.Debug("cache it")
		s.cache.Add(id, user)
	}
	return user, nil
}
